<?php


namespace App\Http\Rest\Shop\Resource;

use App\Http\Rest\Shop\Service\AliPayConfig;
use Framework\Foundation\Request\ServerRequest;
use Framework\Foundation\Log\Log;
use Framework\Foundation\Rest\RestRequestInfo;
use Namshi\Cuzzle\Formatter\CurlFormatter;

class AliPayNotify
{
    /**
     * @param array $restParams
     * @param $request ServerRequest
     */
    public function getList(array $restParams, $request)
    {
        Log::info("ali_notify", [$restParams, $request->getQueryParams(), $request->getParsedBody()]);
        $this->edit($restParams, $request);
    }

    public function getInfo(array $restParams, $request)
    {
    }

    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Envms\FluentPDO\Exception
     */
    public function add(array $restParams, $request)
    {
        $this->edit($restParams, $request);
    }


    public function edit(array $restParams, $request)
    {
        Log::info('notify get ', $_GET);
        Log::info('notify post ', $_POST);
        $curlCommand = (new CurlFormatter())->format($request);
        Log::info('notify curl :' . $curlCommand);

        /**
         * @var $restRequestInfo RestRequestInfo;
         */
        $restRequestInfo = $request->getAttribute('restRequestInfo');
        $routeInfo = $restRequestInfo->getRouteInfo();
        $route = $routeInfo['route'];
        unset($_GET[$route]);
        $route = trim($route, '/');
        unset($_GET[$route]);

        // 实例化继承了接口的类
        $aliPayConf = new AliPayConfig();
        try {
            $client = new \Payment\Client(\Payment\Client::ALIPAY, $aliPayConf->getConfig());
            $xml = $client->notify(new \App\Http\Rest\Shop\Service\AliPayNotify());
            echo $xml;
            exit;
        } catch (\Exception $e) {
            Log::error("支付回调发生错误", ['msg' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            echo $e->getMessage();
            exit;
        }
    }

    public function delete(array $restParams, $request)
    {
    }
}
